package com.example.news.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.news.R;
import com.example.news.bean.TypeDb;
import com.example.news.bean.TypeJson;
import com.example.news.dao.TypeDao;
import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

/**
 * Created by Administrator on 2016/5/17.
 */
public class MyFragment extends Fragment{
    private UMShareAPI umShareAPI;
    private DisplayImageOptions options;
    private ImageView my_logo;
    private TextView username;
    private ImageView header_logo;
    String mPath;
    private ArrayList<TypeJson.MyData> list;
    private ArrayList<TypeDb> query;
    private ArrayList<TypeJson.MyData>  t;
    private TypeDao dao;
    private ListView lv;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.my_frag, null);
        //找控件
        RelativeLayout my_login = (RelativeLayout) view.findViewById(R.id.my_login);
        my_logo = (ImageView) view.findViewById(R.id.my_logo);
        username = (TextView) view.findViewById(R.id.username);
        header_logo = (ImageView) getActivity().findViewById(R.id.header_logo);
        lv =  (ListView) view.findViewById(R.id.my_list);

        //第三方登录
        umShareAPI = UMShareAPI.get(getActivity());

        //获取文件缓存路径
        mPath = getActivity().getCacheDir().getPath();

        //实现圆形图片
        options = new DisplayImageOptions.Builder().displayer(new RoundedBitmapDisplayer(200)).build();

        //登录按钮
        my_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SHARE_MEDIA platform = SHARE_MEDIA.QQ;
                umShareAPI.doOauthVerify(getActivity(), platform, umAuthListener);
            }
        });

        getData();

        return view;
    }
    /**
     * 第三方登录信息
     */
    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            Toast.makeText(getActivity(), "登录成功", Toast.LENGTH_SHORT).show();
            //获取平台信息
            umShareAPI.getPlatformInfo(getActivity(), platform, new UMAuthListener() {
                @Override
                public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {

                    Set<String> set = map.keySet();

                    for (String s:set) {
                        String name = map.get("screen_name");
                        String image_url = map.get("profile_image_url");
                        //将获取的用户头像给控件设置上===用户头像
                        ImageLoader.getInstance().displayImage(image_url, my_logo,options);
                        ImageLoader.getInstance().displayImage(image_url, header_logo,options);
                        //用户昵称
                        username.setText(name);

                        //得到Activity对象
                        //同步程序内的登录信息
                        FragmentActivity activity = getActivity();
                        LeftMenuFragment right = (LeftMenuFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.menu_frame);
                        right.setInfo(image_url,name);
                    }
                }

                @Override
                public void onCancel(SHARE_MEDIA share_media, int i) {

                }

                @Override
                public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {

                }
            });
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText(getActivity(), "登录失败", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Toast.makeText(getActivity(), "已取消登录", Toast.LENGTH_SHORT).show();
        }
    };

    public void setInfo(String url,String name){
        //将获取的用户头像给控件设置上===用户头像
        ImageLoader.getInstance().displayImage(url, my_logo,options);
        ImageLoader.getInstance().displayImage(url, header_logo,options);
        //用户昵称
        username.setText(name);
    }

    /**
     * 获取网络数据
     */
    private void getData() {
        new Thread() {
            @Override
            public void run() {
                HttpUtils httpUtils = new HttpUtils();
                httpUtils.send(HttpRequest.HttpMethod.GET, "http://169.254.25.59:8080/yidian/json/mylist.json", new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        //连接成功，得到数据
                        String json = responseInfo.result;
                        Gson gson = new Gson();
                        TypeJson typeJson = gson.fromJson(json, TypeJson.class);

                        list = typeJson.data;
                        try {
                            //缓存首页数据(对象流)
                            //将第一次请求网络的数据缓存到内存中，方便下次没有网络的时候也可以正常显示
                            ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(mPath));
                            ArrayList<TypeJson.MyData> list = new ArrayList<TypeJson.MyData>();
                            list= typeJson.data;
                            oo.writeObject(list);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        lv.setAdapter(new MyAadpter());
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        try {
                            //从缓存目录中读取数据
                            ObjectInputStream os = new ObjectInputStream(new FileInputStream(mPath));

                            t = (ArrayList<TypeJson.MyData>) os.readObject();

                            lv.setAdapter(new BaseAdapter() {
                                @Override
                                public int getCount() {
                                    return query.size();
                                }

                                @Override
                                public Object getItem(int position) {
                                    return null;
                                }

                                @Override
                                public long getItemId(int position) {
                                    return 0;
                                }

                                @Override
                                public View getView(int position, View convertView, ViewGroup parent) {
                                    View view = View.inflate(getActivity(), R.layout.my_list_item, null);
                                    ImageView iv = (ImageView) view.findViewById(R.id.my_item_iv);
                                    TextView title = (TextView) view.findViewById(R.id.my_item_title);

                                    title.setText(t.get(position).name);
                                    BitmapUtils utils = new BitmapUtils(getActivity());
                                    utils.display(iv,t.get(position).image);
                                    return view;
                                }
                            });
                            Toast.makeText(getActivity(), "当前网络不可用", Toast.LENGTH_SHORT).show();
                        } catch (Exception e1) {
                            e.printStackTrace();
                        }
                        //query = dao.query();

                    }
                });
            }
        }.start();
    }

    /**
     * 自定义适配器
     */
    class MyAadpter extends BaseAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(getActivity(), R.layout.my_list_item, null);
            ImageView iv = (ImageView) view.findViewById(R.id.my_item_iv);
            TextView title = (TextView) view.findViewById(R.id.my_item_title);

            title.setText(list.get(position).name);
            BitmapUtils utils = new BitmapUtils(getActivity());
            utils.display(iv,list.get(position).image);

            return view;
        }
    }
}
